package com.itheima.async;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @program: itheima-jdk8
 * @description:
 * @author: zhanghz001
 * @create: 2021-01-08 14:41
 **/
public class ExecutorCompletionService1 {
    
    public static void main(String[] args) {
        ExecutorService pool = new ThreadPoolExecutor(3, 3,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        
        ExecutorCompletionService<Integer> service = new ExecutorCompletionService<>(pool);
        service.submit(new CalculateArticleScoreA());
        service.submit(new CalculateArticleScoreB());
        service.submit(new CalculateArticleScoreC());
        doSomeThings();
        Integer result = 0;
        for (int i = 0; i < 3; i++) {
            try {
                Future<Integer> take = service.take();
                try {
                    System.out.println(take.get());
                    result += take.get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        pool.shutdown();
        System.out.println(result);
    }
    
    private static void doSomeThings() {
        System.out.println(" main do some things");
    }
    
    private static class CalculateArticleScoreA implements java.util.concurrent.Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            //业务操作
            Random random = new Random();
            
            TimeUnit.SECONDS.sleep(10);
            System.out.println(Thread.currentThread().getName());
            return random.nextInt(100);
        }
    }
    
    private static class CalculateArticleScoreB implements java.util.concurrent.Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            //业务操作
            Random random = new Random();
            
            TimeUnit.SECONDS.sleep(30);
            System.out.println(Thread.currentThread().getName());
            return random.nextInt(100);
        }
    }
    
    private static class CalculateArticleScoreC implements java.util.concurrent.Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            //业务操作
            Random random = new Random();
            
            TimeUnit.SECONDS.sleep(20);
            System.out.println(Thread.currentThread().getName());
            return random.nextInt(100);
        }
    }
}
